package com.xjnt.base.support.admin.shiro.jdbc;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import com.jfinal.aop.Duang;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.xjnt.base.support.admin.entity.Permission;
import com.xjnt.base.support.admin.entity.Role;
import com.xjnt.base.support.admin.service.PermissionService;
import com.xjnt.base.support.admin.service.RoleService;
import com.xjnt.frameworks.plugin.shiro.handler.AuthzHandler;
import com.xjnt.frameworks.plugin.shiro.handler.PermissionJdbcAuthzHandler;
import com.xjnt.frameworks.plugin.shiro.jdbc.AuthzJdbcLoader;

/**
 * @author caoyong
 *
 */
public class ShiroAuthzLoader implements AuthzJdbcLoader {
	
	private static final RoleService roleService = Duang.duang(RoleService.class, Tx.class);
	private static final PermissionService permissionService = Duang.duang(PermissionService.class, Tx.class);
	
	/*
	 * (non-Javadoc)
	 * 
	 * @see com.xjnt.frameworks.plugin.shiro.jdbc.AuthzJdbcLoader#getJdbcAuthz()
	 */
	@Override
	public Map<String, AuthzHandler> getJdbcAuthz() {
		// 按长度倒序排列url
		Map<String, AuthzHandler> dbAuthzMaps = Collections.synchronizedMap(new TreeMap<String, AuthzHandler>(
				new Comparator<String>() {
					public int compare(String firstKey, String secondKey) {
						int result = secondKey.length() - firstKey.length();
						if (result == 0) {
							return firstKey.compareTo(secondKey);
						}
						return result;
					}
				}));
		/**
		 * 权限表必须包含 name code url 字段 url作为key 
		 * 例如 platform		/system/** 
		 * 例如 menu			/system/menus/** 
		 * 例如 function		/system/menus/add**
		 */
		// 获取所有角色
		List<Role> roles = roleService.findAll();
		List<Permission> permissions = null;
		for (Role role : roles) {
			if (role.getInt(Role.AVAILABLE) == 1) {
				permissions = permissionService.findByRoleId(role.getStr(Role.PK_ID));
				for (Permission permission : permissions) {
					if (permission.getInt(Permission.AVAILABLE) == 1) {
						dbAuthzMaps.put(permission.getStr(Permission.URL), new PermissionJdbcAuthzHandler(permission.getStr(Permission.CODE)));
					}
				}
			}
		}
		return dbAuthzMaps;
	}
}
